#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A股股票日线数据同步 - 快速启动脚本
"""
import sys
import os
import argparse
import logging
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from sync_stock_daily import StockDailySync

def setup_logging(verbose=False):
    """设置日志"""
    # 获取项目根目录
    PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
    LOG_DIR = os.path.join(PROJECT_ROOT, 'logs')
    os.makedirs(LOG_DIR, exist_ok=True)
    
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler(os.path.join(LOG_DIR, 'stock_daily_sync.log'), mode='a', encoding='utf-8')
        ]
    )

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='A股股票日线数据同步工具')
    parser.add_argument('--test', action='store_true', help='仅测试功能，不执行同步')
    parser.add_argument('--verbose', '-v', action='store_true', help='详细输出')
    parser.add_argument('--summary', action='store_true', help='仅显示当前数据库状态')
    parser.add_argument('--days', type=int, default=365, help='同步最近N天的数据（默认365天）')
    parser.add_argument('--start-date', help='开始日期（格式：YYYYMMDD）')
    parser.add_argument('--end-date', help='结束日期（格式：YYYYMMDD）')
    parser.add_argument('--stock-codes', nargs='+', help='指定股票代码列表（用空格分隔）')
    parser.add_argument('--limit', type=int, help='限制处理的股票数量（用于测试）')
    
    args = parser.parse_args()
    
    # 设置日志
    setup_logging(args.verbose)
    logger = logging.getLogger(__name__)
    
    try:
        # 创建同步器
        sync = StockDailySync()
        
        if args.summary:
            # 仅显示摘要信息
            print("=" * 60)
            print("A股日线数据数据库状态")
            print("=" * 60)
            
            summary = sync.get_sync_summary()
            if 'error' not in summary:
                print(f"总记录数: {summary['total_records']}")
                print(f"股票数: {summary['total_stocks']}")
                print(f"最新日期: {summary['latest_date']}")
                print(f"最早日期: {summary['earliest_date']}")
                print(f"最后更新: {summary['last_sync']}")
            else:
                print(f"获取状态失败: {summary['error']}")
            return
        
        if args.test:
            # 测试模式
            print("=" * 60)
            print("A股日线数据同步功能测试")
            print("=" * 60)
            
            # 测试获取股票代码
            print("\n1. 测试获取股票代码...")
            try:
                stock_codes = sync.get_stock_codes()
                print(f"✓ 获取到 {len(stock_codes)} 只股票代码")
                print(f"  前5只: {stock_codes[:5]}")
            except Exception as e:
                print(f"✗ 获取股票代码失败: {e}")
                return
            
            # 测试获取单只股票数据
            print("\n2. 测试获取单只股票日线数据...")
            try:
                test_code = stock_codes[0] if stock_codes else "000001"
                start_date = (datetime.now() - timedelta(days=30)).strftime('%Y%m%d')
                end_date = datetime.now().strftime('%Y%m%d')
                
                df = sync.get_daily_data(test_code, start_date, end_date)
                if not df.empty:
                    print(f"✓ 成功获取 {test_code} 的日线数据: {len(df)} 条记录")
                    print(f"  日期范围: {df['trade_date'].min()} - {df['trade_date'].max()}")
                else:
                    print(f"✗ 未获取到 {test_code} 的数据")
                    return
            except Exception as e:
                print(f"✗ 获取日线数据失败: {e}")
                return
            
            # 测试数据库连接
            print("\n3. 测试数据库连接...")
            try:
                summary = sync.get_sync_summary()
                if 'error' not in summary:
                    print(f"✓ 数据库连接成功")
                else:
                    print(f"✗ 数据库连接失败: {summary['error']}")
                    return
            except Exception as e:
                print(f"✗ 数据库连接测试失败: {e}")
                return
            
            print("\n✓ 所有测试通过！")
            return
        
        # 执行同步
        print("=" * 60)
        print("A股股票日线数据同步")
        print("=" * 60)
        print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        
        # 设置日期范围
        start_date = args.start_date
        end_date = args.end_date
        
        if not start_date and args.days:
            start_date = (datetime.now() - timedelta(days=args.days)).strftime('%Y%m%d')
        
        if not end_date:
            # 使用同步器的结束日期逻辑（考虑15点限制）
            sync = StockDailySync()
            end_date = sync.get_sync_end_date()
        
        print(f"同步日期范围: {start_date} - {end_date}")
        
        # 获取股票代码
        stock_codes = args.stock_codes
        if not stock_codes:
            stock_codes = sync.get_stock_codes()
            if args.limit:
                stock_codes = stock_codes[:args.limit]
                print(f"限制处理股票数量: {len(stock_codes)} 只")
        
        print(f"处理股票数量: {len(stock_codes)} 只")
        
        result = sync.sync_daily_data(stock_codes, args.days)
        
        print("\n" + "=" * 60)
        if result['success']:
            print("✓ 同步成功！")
            print(f"处理股票数: {result['total_stocks']} 只")
            print(f"成功股票数: {result['successful_stocks']} 只")
            print(f"失败股票数: {result['failed_stocks']} 只")
            print(f"总记录数: {result['total_records']} 条")
            print(f"同步记录数: {result['synced_records']} 条")
            print(f"同步耗时: {result['duration']:.2f} 秒")
            if result['failed_list']:
                print(f"失败股票: {', '.join(result['failed_list'][:10])}{'...' if len(result['failed_list']) > 10 else ''}")
        else:
            print("✗ 同步失败！")
            print(f"错误信息: {result['error']}")
        print("=" * 60)
        
        # 显示最终状态
        print("\n当前数据库状态:")
        summary = sync.get_sync_summary()
        if 'error' not in summary:
            print(f"总记录数: {summary['total_records']}")
            print(f"股票数: {summary['total_stocks']}")
            print(f"最新日期: {summary['latest_date']}")
            print(f"最早日期: {summary['earliest_date']}")
        
    except KeyboardInterrupt:
        print("\n\n用户中断操作")
    except Exception as e:
        logger.error(f"程序执行失败: {e}")
        print(f"\n程序执行失败: {e}")

if __name__ == "__main__":
    main()
